# -*- encoding: utf-8 -*-
from odoo import models, fields, api


class CreateEstAccountVoucher(models.TransientModel):
    _name = 'create.est.account.voucher'
    _description = u'生成暂估凭证'

    period_id = fields.Many2one('account.period', u'期别', domain="[('gl_state','=','open')]")
    start_date = fields.Date(u'起始日', required=True, )
    end_date = fields.Date(u'截止日', required=True, )

    @api.onchange('period_id')
    def onchange_period_id(self):
        if self.period_id:
            self.start_date = self.period_id.date_start
            self.end_date = self.period_id.date_stop

    def action_confirm(self):
        self.ensure_one()
        domain = [
            ('create_date', '>=', self.start_date),
            ('create_date', '<=', self.end_date),
            ('voucher_id', '=', False),
            ('picking_id', '!=', False)
        ]
        scrip_lines = self.env['account.voucher.script.line'].search(domain)
        sudo_picking = scrip_lines.mapped('picking_id')
        sudo_picking.generate_account_voucher()
        return {
            'name': '暂估凭证',
            'type': 'ir.actions.act_window',
            'view_mode': 'tree',
            'res_model': 'account.voucher',
        }
